package com.koron.css2.baseConfig.impl;

import com.koron.css2.ServerInterface;
import com.koron.css2.baseConfig.bean.BankBean;
import com.koron.css2.baseConfig.mapper.BankMapper;
import com.koron.css2.serviceManage.bean.RequestBean;
import com.koron.css2.serviceManage.bean.UserInfoBean;
import com.koron.css2.serviceManage.utils.CommonUtils;
import com.koron.util.Constant;
import com.koron.util.JsonUtils;
import com.koron.util.ValidationKey;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.koron.ebs.mybatis.SessionFactory;
import org.swan.bean.MessageBean;

/**
 * 添加银行信息
 *
 * @author 廖大富
 */
public class BankAdd implements ServerInterface {

    private static Logger logger = LogManager.getLogger(BankAdd.class);

    @Override
    @ValidationKey(clazz = BankBean.class,method = "insert")
    public MessageBean<?> exec(SessionFactory factory, UserInfoBean userInfo, RequestBean req) {
        BankMapper mapper = factory.getMapper(BankMapper.class);
        try {
            BankBean bean = JsonUtils.objectToPojo(req.getData(), BankBean.class);
            bean.setCreateInfo(userInfo);
            handCode(mapper, bean);
            mapper.saveBank(bean);
        } catch (Exception e) {
            logger.error("添加银行信息失败", e);
            return MessageBean.create(Constant.ILLEGAL_PARAMETER, "添加银行信息失败", void.class);
        }
        return MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "success", void.class);
    }

    /**
     * 自动生成分级code
     *
     * @param mapper
     * @param bean
     */
    public static void handCode(BankMapper mapper, BankBean bean) {
        // 生成code, 规则5位一级，下级自动继承上级
        String parentNo = bean.getBankNo();
        BankBean parentBean = null;
        if (StringUtils.isNotBlank(bean.getParentId()) && !bean.getParentId().equals("0")) {
            parentBean = mapper.findBankById(bean.getParentId()); // 通过id查询数据
            parentNo = parentBean.getBankNo();
        }
        // 取父级目录下最大的下级目录
        String maxCode = mapper.findMaxChild(parentNo);// 通过行政区域编号查询
        if (StringUtils.isBlank(maxCode)) {// 如果未找到，说明下面没有子级，给初始值
            maxCode = parentNo + "00000";
        }
        // 未位加1
        long last5 = Long.parseLong("1" + maxCode.substring(maxCode.length() - 5)) + 1;
        maxCode = maxCode.substring(0, maxCode.length() - 5) + (last5 + "").substring(1);
        // 重设code
        bean.setBankNo(maxCode);
        bean.setIsLeaf(1);// 新增加的数据，都是叶结点
        // 自动更新其上级为目录
        if (parentBean != null) {
            parentBean.setIsLeaf(0);
            parentBean.setUpdateTime(CommonUtils.getCurrentTime());
            mapper.updateBank(parentBean);
        }
    }
}
